package cuda;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import org.antlr.runtime.tree.CommonTreeNodeStream;

public class Main {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {

		// TODO: wczytanie nazwy pliku z linii komend
		String inputFileName = "data/input.txt";
		String outputFileName = "data/output.cpp";

		// TODO: Uzaleznic od uzytkownika
		String LIB_NAME = "cpu.lib";

		CudaLexer cudaLexer = null;
		try {
			cudaLexer = new CudaLexer(new ANTLRFileStream(inputFileName));
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Error: could not read input from file");
			return;
		}

		try {
			TokenStream tokenStream = new CommonTokenStream(cudaLexer);
			CudaParser cudaParser = new CudaParser(tokenStream);
			CudaParser.program_return program = cudaParser.program();

			CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(
					program.tree);
			TreeWalker walker = new TreeWalker(nodeStream);
			
			FileWriter out = new FileWriter(outputFileName);
			out.write(walker.program().app);
			out.close();

			createBat(outputFileName, LIB_NAME);
		} catch (RecognitionException e) {
			e.printStackTrace();
			System.out.println("Recognition error");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Error writing output to file");
		}
	}

	private static void createBat(String fileName, String libName)
			throws IOException {

		File sourceFile = new File(fileName);
		String prefix = sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf('.'));
		
		File batFile = new File(sourceFile.getParentFile(), "compile_"+ prefix + ".bat");

		FileWriter out = new FileWriter(batFile);
		out.write("@echo off\n");
		out.write("call \"C:\\Program Files (x86)\\Microsoft Visual Studio 8\\VC\\bin\"\\vcvars32.bat\n");
		out.write("cl.exe /EHsc /nologo /O2 /I../backends/inc ../backends/bin/"+libName+" "+sourceFile.getName()+" -o "+prefix+".exe\n");
		out.write("del "+prefix+".obj\n");
		out.close();

	}
}
